package com.example.project.projectspringcloud.common.wechat;

import com.example.project.projectspringcloud.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author www.inxedu.com
 */
public class PackageUtil {

    /**
     * 特殊字符处理
     * ==============================================================================
     *
     * @param src
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlEncode(String src) throws UnsupportedEncodingException {
        return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
    }

    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public static String createSign(SortedMap<String, String> packageParams, String payKey) {
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<String, String>> es = packageParams.entrySet();
        Iterator<Map.Entry<String, String>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (StringUtils.isNotBlank(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + payKey);
        String sign = StringUtil.md5(sb.toString()).toUpperCase();

        return sign;

    }

    public static String getNonceStr() {
        Random random = new Random();
        return StringUtil.md5(String.valueOf(random.nextInt(10000)));
    }

    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
}
